package cn.wzptsoft.mall.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

@Component
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {



    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        System.out.println("-----------------------------------------------------CustomAuthenticationEntryPoint");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type","application/json; charset=utf-8");
        StringBuilder sb=new StringBuilder("CustomAuthenticationEntryPoint错误信息: ");
        // 用户登录时身份认证未通过
        if (authException instanceof BadCredentialsException) {
            log.info("用户登录时身份认证失败!");
            sb.append("用户登录时身份认证失败");
        } else if (authException instanceof InsufficientAuthenticationException) {//测试中只有这里生效
            log.info("缺少请求头参数,Authorization传递是token值所以参数是必须的.");
            sb.append("缺少请求头参数");
        } else {
            log.info("用户token无效.");
            sb.append("用户token无效");
        }
        response.getWriter().println(sb);
    }
}